package com.br.planningrun.repositorio;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.br.planningrun.entidade.Exercicio;

public class RepositorioExercicio {
	// Atributos
	private Context context;
	private SQLiteDatabase db2 = null;
	private SQLiteStatement stmt = null;
	private Cursor c = null;
	
	private static final String NOME_TABELA = "tb_Exercicio";
	private static final String BANCO = "planningrun";
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private RepositorioTipoTempo repositorioTipoTempo = null;
	private RepositorioTipoExercicio repositorioTipoExercicio = null;
	
	// Construtor
	public RepositorioExercicio(Context context){
		this.context = context;
		repositorioTipoTempo = new RepositorioTipoTempo(context);
		repositorioTipoExercicio = new RepositorioTipoExercicio(context);
	}	

	public int getMaxId() {
		int retorno = 0;
		try {
			db2 = context.openOrCreateDatabase(BANCO, 0, null);
			c = db2.rawQuery("SELECT MAX(codigo) as maximo FROM " + NOME_TABELA + ";",
					null);

			c.moveToNext();
			retorno = c.getInt(c.getColumnIndex("maximo"));
			
    	} finally {
    		if (stmt != null) {
        		stmt.close();
        	}
        	
        	if (c != null) {
        		c.close();
        	}
        	
        	if (db2 != null) {
        		db2.close();
        	}
    	}
		
		return retorno;

	}
	
	// Inserir objeto
	public void inserir(Exercicio Exercicio){
		try {
			db2 = context.openOrCreateDatabase(BANCO, 0, null);

			stmt = db2.compileStatement("INSERT INTO " 
					+ NOME_TABELA + " (codigo,duracao,tipoTempo, tipoExercicio, treino) VALUES (?,?,?,?,?)");
			
			stmt.bindLong(1, Exercicio.getCodigo());
			stmt.bindDouble(2, Exercicio.getDuracao().doubleValue());
			stmt.bindLong(3, Exercicio.getTipoTempo().getCodigo());
			stmt.bindString(4, Exercicio.getTipoExercicio().getSigla());
			stmt.bindLong(5, Exercicio.getTreino().getCodigo());

			stmt.execute();
    	} finally {
    		if (stmt != null) {
        		stmt.close();
        	}
        	
        	if (c != null) {
        		c.close();
        	}
        	
        	if (db2 != null) {
        		db2.close();
        	}
    	}
	}

	// Atualizacao do objeto
	public void atualizar(Exercicio Exercicio) {
		try {
			db2 = context.openOrCreateDatabase(BANCO, 0, null);

			stmt = db2.compileStatement("UPDATE " + NOME_TABELA 
					+ " SET " + "duracao = ?, tipoTempo = ? , tipoExercicio = ? , treino = ? WHERE codigo = ?;");

			stmt.bindDouble(1, Exercicio.getDuracao().doubleValue());
			stmt.bindLong(2, Exercicio.getTipoTempo().getCodigo());
			stmt.bindString(3, Exercicio.getTipoExercicio().getSigla());
			stmt.bindLong(4, Exercicio.getTreino().getCodigo());
			stmt.bindLong(5, Exercicio.getCodigo());

			
			stmt.execute();
    	} finally {
    		if (stmt != null) {
        		stmt.close();
        	}
        	
        	if (c != null) {
        		c.close();
        	}
        	
        	if (db2 != null) {
        		db2.close();
        	}
    	}
	}


	// Remover objeto (CODIGO)
	public void remover(int codigo) {
		try {
			db2 = context.openOrCreateDatabase(BANCO, 0, null);

			stmt = db2.compileStatement("DELETE FROM " 
					+ NOME_TABELA + " WHERE codigo = ?;");

			stmt.bindLong(1, codigo);

			stmt.execute();
    	} finally {
    		if (stmt != null) {
        		stmt.close();
        	}
        	
        	if (c != null) {
        		c.close();
        	}
        	
        	if (db2 != null) {
        		db2.close();
        	}
    	}
	}

	// Remover objeto (WHERE)
	public void remover(String where) {
		try {
			db2 = context.openOrCreateDatabase(BANCO, 0, null);

			stmt = db2.compileStatement("DELETE FROM " 
					+ NOME_TABELA + " " + where);

			stmt.execute();
    	} finally {
    		if (stmt != null) {
        		stmt.close();
        	}
        	
        	if (c != null) {
        		c.close();
        	}
        	
        	if (db2 != null) {
        		db2.close();
        	}
    	}
	}

	// Consulta do objeto (CODIGO)
	public Exercicio procurar(int codigo) {
		ArrayList<Exercicio> lista = this.listar(" WHERE codigo = " + codigo);
		Exercicio Exercicio = null;
		if (lista.size() > 0) {
			Exercicio = lista.get(0);
		}
		return Exercicio;
	}

	// Listagem dos objetos
	public ArrayList<Exercicio> listar(String where) {
		ArrayList<Exercicio> lista = new ArrayList<Exercicio>();
		
		try {
			db2 = context.openOrCreateDatabase(BANCO, 0, null);
			c = db2.rawQuery("SELECT * FROM " + NOME_TABELA + " " + where + ";",
					null);

			while (c.moveToNext()) {
				Exercicio Exercicio = new Exercicio();
				Exercicio.setCodigo(c.getInt(c.getColumnIndex("codigo")));

				Exercicio.setDuracao(new BigDecimal(c.getDouble(c.getColumnIndex("duracao"))));

				int idTipoTempo = c.getInt(c.getColumnIndex("tipoTempo"));
				Exercicio.setTipoTempo(this.repositorioTipoTempo.procurar(idTipoTempo));

				String idTipoExercicio = c.getString(c.getColumnIndex("tipoExercicio"));
				Exercicio.setTipoExercicio(this.repositorioTipoExercicio.procurar(idTipoExercicio));

				lista.add(Exercicio);
			}
    	} finally {
    		if (stmt != null) {
        		stmt.close();
        	}
        	
        	if (c != null) {
        		c.close();
        	}
        	
        	if (db2 != null) {
        		db2.close();
        	}
    	}
		
		return lista;
	}

	// Criacao da tabela
	public void truncate() {
		try {
			db2 = context.openOrCreateDatabase(BANCO, 0, null);
			// Exclusao da tabela se existir
			db2.execSQL("DROP TABLE IF EXISTS " + NOME_TABELA);
			// Criacao da tabela
			db2.execSQL("CREATE TABLE IF NOT EXISTS " + NOME_TABELA + "( codigo INTEGER NOT NULL PRIMARY KEY,"
					+ "duracao INTEGER,"
					+" tipoTempo INTEGER,"
					+" tipoExercicio varchar(255),"
					+" treino INTEGER"
					+ ");");
    	} finally {
    		if (stmt != null) {
        		stmt.close();
        	}
        	
        	if (c != null) {
        		c.close();
        	}
        	
        	if (db2 != null) {
        		db2.close();
        	}
    	}
	}
}
